package sdm.sensor.nasdaq;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import java.io.*;

import org.cloudminer.sensor.MyParameter;
import org.cloudminer.sensor.MySample;
import org.cloudminer.sensor.MySensor;

import org.apache.log4j.*;

import com.espertech.esper.client.*;


//import java.util.Arrays;



public class NasdaqApp {

	public static void main(String args[]) {
	
		
		// redirect 'System.out' to file
		boolean redirect = false;
		
		if (redirect) {
			PrintStream defaultStream 	= null;
			PrintStream newStream 	= null;
			
			try {
				// saving the default stream
				defaultStream = System.out;
				newStream = new PrintStream(new FileOutputStream("NASDAQ.txt",true));
				// redirecting console output to file
				System.setOut(newStream);
				// redirecting runtime exceptions to file
				System.setErr(newStream);
			}
			catch (FileNotFoundException fnfEx)
			{
				System.out.println("Error in IO Redirection");
				fnfEx.printStackTrace();
				
				// resetting stream (although it shouldn't have changed at this point...)
				System.setOut(defaultStream);
				System.setErr(defaultStream);
			}
		}
			
		// print timestamp
		DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        Date date = new Date();
        System.out.println(dateFormat.format(date).toString());
		
		// init log4j
		SimpleLayout layout = new SimpleLayout();
		ConsoleAppender appender = new ConsoleAppender(layout);
		Logger.getRootLogger().addAppender(appender);
		Logger.getRootLogger().setLevel((Level) Level.ERROR);
		
		// instances of org.cloudminer
		MySensor mySensor = new MySensor();
		MyParameter myParameter = new MyParameter();
		MySample mySample = null;
		

		System.out.println("NASDAQ 'AAPL'");		
		// Parameter for the Sensor: a company code (AAPL for Apple Inc.)
		myParameter.setParameter("AAPL");
		
		// esper
		EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider();
		
		
		// Statement 'average' --> get the average of a 20sec window after every event
		String averageExpression = 
				"select avg(value) from org.cloudminer.sensor.MySample.win:time(20 sec)";
		EPStatement averageStatement = 
				epService.getEPAdministrator().createEPL(averageExpression);
				
		// Listener 'average'
		averageStatement.addListener(
			new UpdateListener() { // Interface UpdateListener (inner class)
				public void update(EventBean[] newEvents, EventBean[] oldEvents) {
					EventBean event = newEvents[0];
					System.out.println("\n avg = " + event.get("avg(value)"));
				}
			}
		);
		
		
		// Statement 'max & deltaMax' - get the maximum and change of maximum
		String maxExpression =		
			"select cur.value, max(cur.value) as maxVal," + 
			"max(cur.value) - max(prior(1,cur.value)) as deltaMax "+
			"from org.cloudminer.sensor.MySample.win:time_batch(5 sec) cur";
		EPStatement maxStatement = epService.getEPAdministrator().createEPL(maxExpression);
		
		// Listener 'max & deltaMax' 
		maxStatement.addListener(
			new UpdateListener() { 
				public void update(EventBean[] newEvents, EventBean[] oldEvents) {
					EventBean event = newEvents[0];
					System.out.println("\n max of 5sec batch = " + event.get("maxVal"));
					System.out.println(" delta to last maximum = " + event.get("deltaMax"));
					// Using 'prior' instead of 'oldEvents'
//					if(oldEvents != null) {
//						EventBean oldEvent = oldEvents[0];					
//						System.out.println("oldMax=" + event.get("max(value)"));
//					}
					
				}
			}
		);
		
		
		// get 30 samples
		for(int index = 1; index <= 30;  index++) {
		
			System.out.println("\n--------------");
			System.out.println("Event Number" + index);
			System.out.println("--------------");
			
			// get Sample
			mySample = mySensor.generateSample(MySensor.SENSOR_NAME_NASDAQ, myParameter);
		
			// manual test sample
//			mySample.setValue(index);
							
			// esper Event
			epService.getEPRuntime().sendEvent(mySample);
						
			// wait
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
		
}
